package ece452.ims.view;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import ece452.ims.connection.*;

public class AddRemoveFriend extends JPanel {

	private static Relay rl;
	private JTextField unameField;
	private JComponent message;
	private String label;
	public String addF="", remF="";
	private int choice;
	
	public AddRemoveFriend(Relay r, int n){
		this.rl = r;
		this.choice = n;
		unameField = new JTextField(15);
		label="";
		
		switch(n){
		case 1:	// account already exists
			message = makeTextPanel("Add a new friend.");
			label = "Add";
			break;
		case 2:
			message = makeTextPanel("Remove a friend.");
			label = "Remove";
			break;
		default:
			message = makeTextPanel("initializer");
			break;
		}
		JButton ok = new JButton(label);
		ok.setEnabled(true);
		ok.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(choice == 1){
					addF = unameField.getText();
					rl.addFriend(addF);
				}else{
					remF = unameField.getText();
					rl.removeFriend(remF);
				}
			}
		});
		
		JPanel headerPanel = new JPanel();
		headerPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
		headerPanel.add(message);
		headerPanel.setBorder(BorderFactory.createEmptyBorder(20,0,0,0));
		
		JPanel unamePanel = new JPanel();
		unamePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		unamePanel.add(unameField);
		unamePanel.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
		
		JPanel okButton = new JPanel();
		okButton.setLayout(new FlowLayout(FlowLayout.CENTER));
		okButton.add(ok);
		okButton.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
		
		add(headerPanel);
		add(unamePanel);
		add(okButton);
		
	}
	
	protected JComponent makeTextPanel(String text) {
		JPanel panel = new JPanel(true);
		JLabel filler = new JLabel(text);
		filler.setHorizontalAlignment(JLabel.CENTER);
		panel.setLayout(new GridLayout(1, 1));
		panel.add(filler);
		return panel;
	}
	
	public static void showGUI() {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		JFrame frame = new JFrame("Instant Messaging Service Login");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setPreferredSize(new Dimension(200, 350));
		frame.setLocation(screenSize.height/2, screenSize.width/6);
		frame.getContentPane().add(new AddRemoveFriend(null,2), BorderLayout.CENTER);
		frame.pack();
		frame.setVisible(true);
		frame.setResizable(false);
	}

	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() { showGUI(); }
		});
	}
	
}
